package main

import (
	"fmt"
	"log"
	"math/rand"
	"simple-crm/config"
	"simple-crm/models"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

// generateOperationLogs 生成操作日志测试数据
func generateOperationLogs() {
	// 加载配置
	cfg := config.Load()

	// 连接数据库
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=True&loc=Local",
		cfg.Database.User,
		cfg.Database.Password,
		cfg.Database.Host,
		cfg.Database.Port,
		cfg.Database.Name,
		cfg.Database.Charset,
	)

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatal("连接数据库失败:", err)
	}

	// 获取所有用户ID
	var userIDs []uint
	db.Model(&models.User{}).Pluck("id", &userIDs)
	if len(userIDs) == 0 {
		log.Fatal("没有找到用户数据")
	}

	// 定义操作类型和资源类型
	actions := []string{"create", "update", "delete", "view", "login", "logout", "push", "export"}
	resources := []string{"user", "role", "permission", "customer", "partner", "push"}
	ipAddresses := []string{"192.168.1.100", "10.0.0.50", "172.16.0.25", "127.0.0.1"}
	userAgents := []string{
		"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
		"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
		"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36",
	}

	// 生成100条操作日志
	rand.Seed(time.Now().UnixNano())
	for i := 0; i < 100; i++ {
		// 随机选择用户
		userID := userIDs[rand.Intn(len(userIDs))]
		
		// 随机选择操作和资源
		action := actions[rand.Intn(len(actions))]
		resource := resources[rand.Intn(len(resources))]
		
		// 生成随机时间（最近30天内）
		createdAt := time.Now().AddDate(0, 0, -rand.Intn(30))
		
		// 生成详细信息
		details := fmt.Sprintf("%s了%s资源", getActionText(action), getResourceText(resource))
		
		operationLog := models.OperationLog{
			UserID:     userID,
			Action:     action,
			Resource:   resource,
			ResourceID: getRandomResourceID(),
			Details:    details,
			IPAddress:  ipAddresses[rand.Intn(len(ipAddresses))],
			UserAgent:  userAgents[rand.Intn(len(userAgents))],
			CreatedAt:  createdAt,
		}
		
		if err := db.Create(&operationLog).Error; err != nil {
			log.Printf("创建操作日志失败: %v", err)
			continue
		}
		
		if (i+1)%10 == 0 {
			fmt.Printf("已生成 %d 条操作日志\n", i+1)
		}
	}
	
	fmt.Println("操作日志测试数据生成完成！")
}

// getActionText 获取操作文本
func getActionText(action string) string {
	actionMap := map[string]string{
		"create": "创建",
		"update": "更新",
		"delete": "删除",
		"view":   "查看",
		"login":  "登录",
		"logout": "登出",
		"push":   "推送",
		"export": "导出",
	}
	if text, ok := actionMap[action]; ok {
		return text
	}
	return action
}

// getResourceText 获取资源文本
func getResourceText(resource string) string {
	resourceMap := map[string]string{
		"user":       "用户",
		"role":       "角色",
		"permission": "权限",
		"customer":   "客户",
		"partner":    "合作机构",
		"push":       "推送",
	}
	if text, ok := resourceMap[resource]; ok {
		return text
	}
	return resource
}

// getRandomResourceID 获取随机资源ID
func getRandomResourceID() *uint {
	id := uint(rand.Intn(100) + 1)
	return &id
}

func main() {
	generateOperationLogs()
}